﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Apollo.Web
{
    public class SessionEntityView
    {
        protected const string SESSION_ENTITY_VIEW_KEY = "SessionEntityView";
        protected const string SESSION_ENTITY_VIEW_INDEX_KEY = "SessionEntityViewIndex";

        public static EntityView Pop(int id) {
            if (id > 0)
                return Apollo.Application.Meta<EntityView>()
                        .SingleOrDefault<EntityView>(e => e.Id == id);

            if (HttpContext.Current.Session[SESSION_ENTITY_VIEW_KEY] == null)
                return null;

            IList<EntityView> entityViews = HttpContext.Current.Session[SESSION_ENTITY_VIEW_KEY] as IList<EntityView>;

            return entityViews.FirstOrDefault<EntityView>(ev => ev.Id == id);
        }

        public static void Push(EntityView view) {
            if (view.Id > 0)
                return;

            IList<EntityView> entityViews = HttpContext.Current.Session[SESSION_ENTITY_VIEW_KEY] as IList<EntityView>;

            if (entityViews == null)
                entityViews = new List<EntityView>();

            // calculate a new id for the view
            int newId = HttpContext.Current.Session[SESSION_ENTITY_VIEW_INDEX_KEY] == null ?
                -10 :
                (int)HttpContext.Current.Session[SESSION_ENTITY_VIEW_INDEX_KEY] - 1;

            if (newId >= -10)
            {
                HttpContext.Current.Session.Add(SESSION_ENTITY_VIEW_INDEX_KEY, -10);
                newId = -10; // in case that if finds a bigger value in the session
            }
            else
                HttpContext.Current.Session[SESSION_ENTITY_VIEW_INDEX_KEY] = newId;

            // assign a new id to the view
            view.Id = newId;

            // add it to list
            entityViews.Add(view);

            // save it to Session
            if (HttpContext.Current.Session[SESSION_ENTITY_VIEW_KEY] == null)
                HttpContext.Current.Session.Add(SESSION_ENTITY_VIEW_KEY, entityViews);
            else
                HttpContext.Current.Session[SESSION_ENTITY_VIEW_KEY] = entityViews;
        }
    }
}
